<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>WebSocket测试</title>
</head>
<body>
<label for="clientId">
    <input id="clientId" type="text" placeholder="请输入客户端ID">
</label>
<button id="btn1" onclick="connect()">连接</button>
<br/>
<label for="receiver">
    <input id="receiver" type="text" placeholder="请输入用户ID">
</label>
<label for="content">
    <input id="content" type="text" placeholder="请输入内容">
</label>
<button id="btn2" onclick="send()">发送</button>
</body>
<script>

	let socket

    function connect() {

        let clientId = getClientId();

        socket = new WebSocket("ws://127.0.0.1:1112/ws")

        socket.onopen = function() {
            alert("连接成功")
            console.log("连接成功")
			socket.send(JSON.stringify({type: 'connect', payload: clientId}))
        }

        socket.onmessage = function(event) {
			const data = event.data;
			if (data === 'ping') {
				console.log('接收心跳ping')
				console.log('发送心跳pong')
				socket.send(JSON.stringify({type: 'pong', payload: 'pong'}))
			} else {
				alert("接收消息：" + data)
				console.log("接收消息", data)
			}
        }

        socket.onerror = function(event) {
            alert("连接失败")
            console.log("连接失败", event)
        }

        socket.onclose = function() {
            alert("连接关闭")
            console.log("连接关闭")
        }

    }

    function send() {
		const payload = {
			receivers: [getReceiver()],
			content: getContent()
		}
		socket.send(JSON.stringify({type: 'message', payload: payload}))
	}

    function getClientId() {
        return document.getElementById("clientId").value
    }

    function getReceiver() {
        return document.getElementById("receiver").value
    }

    function getContent() {
        return document.getElementById("content").value
    }

</script>
</html>
